package com.zlyx.easy.redis.config;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

/**
 * <p>
 * 缓存配置
 * </p>
 *
 * @author zg
 */
@Configuration
@EnableCaching
@ConfigurationProperties("easy.cache")
@ConditionalOnExpression("${easy.cache.active:true}")
public class CacheConfig {

	private static final Logger logger = LoggerFactory.getLogger(CacheConfig.class);

	private boolean allowNullValue = false;

	private long globalCacheTime = 30L;

	private Map<String, Long> cacheTimes = new HashMap<>();

	@Bean
	@ConditionalOnMissingBean
	public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
		RedisSerializer<String> redisSerializer = new StringRedisSerializer();
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
				Object.class);

		// 解决查询缓存转换异常的问题
		ObjectMapper om = new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
		om.registerModule(new JavaTimeModule());
		jackson2JsonRedisSerializer.setObjectMapper(om);

		// 配置序列化（解决乱码的问题）
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
				.entryTtl(Duration.ofSeconds(globalCacheTime))
				.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
				.serializeValuesWith(
						RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
		if (!allowNullValue) {
			config.disableCachingNullValues();
		}
		Map<String, RedisCacheConfiguration> cacheConfig = new HashMap<>();
		if (cacheTimes != null && !cacheTimes.isEmpty()) {
			cacheTimes.forEach((cacheName, expireTime) -> {
				cacheConfig.put(cacheName,
						RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(expireTime))
								.serializeKeysWith(
										RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
								.serializeValuesWith(RedisSerializationContext.SerializationPair
										.fromSerializer(jackson2JsonRedisSerializer)));
			});
			logger.info("cacheConfig.{}", cacheConfig);
		}
		return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config)
				.withInitialCacheConfigurations(cacheConfig).build();
	}

}
